package com.leyou.user.controller;

import com.leyou.common.exceptions.LyException;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @Auther: xiang
 * @Date: 2019/8/28 17:11
 * @Description:
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 校验数据是否可用
     * @param date
     * @param type
     * @return
     */
    @GetMapping("check/{date}/{type}")
    public ResponseEntity<Boolean> checkUserDate(
            @PathVariable("date") String date,
            @PathVariable("type") Integer type
    ){
       return ResponseEntity.ok(userService.checkDate(date,type));


    }

    /**
     * 发送验证码短信
     * @param code
     * @return
     */
    @PostMapping("code")
    public ResponseEntity<Void> senCode(@RequestParam("phone")String code){
        userService.sendCode(code);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();


    }

    /**
     * 注册用户
     * @param user 用户输入的 username password 以及phone
     * @param code 验证码
     * @return
     */
    @PostMapping("register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam("code") String code){
        if (result.hasErrors()) {
            String msg = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            throw new LyException(400,msg);
        }
        userService.registerUser(user, code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 给你一个用户查询数据库有没有
     * @return
     */
    @GetMapping("query")
    public ResponseEntity<UserDTO> queryUser(@RequestParam("username")String username, @RequestParam("password")String password ){

        return ResponseEntity.ok(userService.queryUser(username,password));


    }

}